import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/Home.vue'
import Store from '@/store'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView
  },
  {
    path: '/all',
    name: 'all',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "all" */ '../views/All.vue')

  },
  {
    path: '/ures',
    name: 'Ures',
    redirect: "/ures/cart",
    component: () => import(/* webpackChunkName: "ures" */ '../views/Ures.vue'),
    children: [
      {
        path: 'cart',
        name: 'Cart',
        component: () => import(  /* webpackChunkName: "Cart" */ '@/components/ures/Cart.vue'),
      },
      {
        path: 'center',
        name: 'Center',
        component: () => import(  /* webpackChunkName: "center" */ '@/components/ures/Center.vue'),
      }
    ]
  },
  {
    path: '/order',
    name: 'Order',
    component: () => import(/* webpackChunkName: "order" */ '../views/Order.vue')
  },
  {
    path: '/free',
    name: 'Free',
    component: () => import(/* webpackChunkName: "free" */ '../views/Free.vue')
  },
  {
    path: '/products/:id',
    name: 'ProductDetails',
    component: () => import(/* webpackChunkName: "products" */ '@/components/ProductDetails.vue')
  }
]
// 重复点击跳转同一个页面报错解决
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// router.beforeResolve((to, from, next) => {
router.beforeEach((to, from, next) => {
  if (to.path === '/ures') {
    // 当用户想要跳转到 用户 /ures页面时
    // 判断用户是否登录  --判断 token 是否存在
    let token = localStorage.getItem('x-auth-token')
    if (token) {
      // 进行token 的鉴权，然后再去判断是否可以继续跳转
      // 我们这里只判断没有token
      next()
    } else {
      // 给提示
      let toastObj = {
        content: '请先登录',
        icon: "success",
      };
      Store.dispatch("AsyncToast", toastObj);
      Store.commit("changeIsOpenLogin", true);
    }
    return
  }
  next()
})

export default router
